package com.example.understand_compose1.fet_okhttpusage

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.understand_compose1.R
import com.example.understand_compose1.databinding.ActivityFetOkHttpBinding
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException

class FetOkHttpActivity : AppCompatActivity() {
    lateinit var binding: ActivityFetOkHttpBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        binding = ActivityFetOkHttpBinding.inflate(layoutInflater)

        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


    }

    fun okhttpFetch(view: View) {
        // TODO:GET 请求, POST请求使用FormBody
        // 1. 创建OkHttpClient
        val client = OkHttpClient()
        // 2. 创建Request
        val request = Request.Builder()
            .url("https://v2.jinrishici.com/token") // BUG: 请求过大的数据如http://baidu.com直接闪退
            .build()

        //3. 发送请求并处理响应,异步enqueue,同步execute
        client.newCall(request).enqueue(object : okhttp3.Callback {
            override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                runOnUiThread {
                    // 4. 得到返回的数据
                    if (response.isSuccessful) {
                        val resp = response.body?.string()
                        binding.tv1.text = resp
                    } else {
                        runOnUiThread {
                            Toast.makeText(
                                this@FetOkHttpActivity,
                                "Failed to fetch data: ${response.code}",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
            }

            override fun onFailure(call: okhttp3.Call, e: IOException) {
                runOnUiThread {
                    e.printStackTrace()
                }
            }
        })
    }
}